from django.conf import settings
from django.core.management.base import BaseCommand
from django.template.loader import render_to_string
from django.template import Context
from optparse import make_option
from django.contrib.auth.models import User
from hosting.hosts.models import Host, HostAlias
from hosting.system.user import process_user
from hosting.system.file import process_dir

class Command( BaseCommand ):
    option_list = BaseCommand.option_list + (
        make_option('--printout', action='store_true', dest='count', default= False,
            help='Print config in stdout' ),
    )
    help = 'Generate config with virtual hosts.'
    args = '[username ...]'

    requires_model_validation = True

    def render_host(self, host, template, user, settings):
        context = Context()
        context['user'] = user
        context['proxy_host'] = settings.HOSTING_PROXY_HOST
        context['real_host'] = settings.HOSTING_REAL_HOST
        context['host'] = host
        host_aliases = HostAlias.objects.filter(host=host)
        context['host_aliases'] = host_aliases
        return render_to_string(template,context)

    def handle(self, *args, **options):
        files = {}
        status = ""
            
        if len(args) == 0:
            users = User.objects.all()
            for template in settings.HOSTING_TEMPLATES:
                files[template[0]] = open(template[1]+'/'+template[0],'w')
            for user in users:
                process_user(user.username, settings.HOSTING_GROUP,settings.HOSTING_HOME,settings.HOSTING_SHELL)
                status+='Process user '+user.username+'\n'
                hosts = Host.objects.filter(user=user)
                for host in hosts:
                    process_dir(settings.HOSTING_HOME+'/'+user.username+'/www/'+host.name, user.username, settings.HOSTING_GROUP, '0755')
                    status+='\tProcess directory for vhost '+host.name+'\n'
                    for template in settings.HOSTING_TEMPLATES:
                        files[template[0]].write(self.render_host(host, template[0], user, settings))
                    status+='\tGenerate vhost '+host.name+' for user '+user.username+' success\n'
            for template in settings.HOSTING_TEMPLATES:
                files[template[0]].close()

        else:
            for username in args:
                try:
                    user = User.objects.get(username=username)
                    hosts = Host.objects.filter(user=user)
                    process_user(user.username, settings.HOSTING_GROUP,settings.HOSTING_HOME,settings.HOSTING_SHELL)
                    status+='Process user '+user.username+'\n'
                    for template in settings.HOSTING_TEMPLATES:
                        files[template[0]] = open(template[1]+'/'+user.username+'-'+template[0],'w')
                        for host in hosts:
                            process_dir(settings.HOSTING_HOME+'/'+user.username+'/www/'+host.name,user.username,settings.HOSTING_GROUP,'0755')
                            status+='\tProcess directory for vhost '+host.name+'\n'
                            files[template[0]].write(self.render_host(host, template[0], user, settings))
                            status+='\tGenerate vhost '+host.name+' for user '+user.username+' success\n'
                        files[template[0]].close()
                        status += "Generate file "+user.username+'-'+template[0]+" success.\n"
                except:
                    status += "User "+username+" don't exist!\n"
        return status
